package cc.dullsky.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtil {
	/**
	 * 下载网络文件
	 * 
	 * @param urlStr
	 *            下载地址
	 * @param fileName
	 *            文件名
	 * @param savePath
	 *            保存路径
	 * @return boolean
	 */
	public static boolean downLoadFromUrl(String urlStr, String fileName, String savePath) {
		try {
			File saveDir = new File(savePath);
			if (!(saveDir.exists())) {
				saveDir.mkdir();
			}
			File file = new File(saveDir + File.separator + fileName);
			if (!(file.exists())) {
				URL url = new URL(urlStr);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(10000);
				conn.setRequestProperty("User-Agent",
						"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
				InputStream inputStream = conn.getInputStream();
				FileOutputStream fos = new FileOutputStream(file);
				byte[] temp = new byte[1024];
				int len;
				while ((len = inputStream.read(temp)) != -1) {
					fos.write(temp, 0, len);
				}
				fos.close();
				inputStream.close();
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
